<template>
  <div>
    <van-nav-bar
      title="支付中..."
      left-text="返回"
      left-arrow
      @click-left="goBack"
    >
      <template #right>
        <van-icon name="wap-nav" size="18" />
      </template>
    </van-nav-bar>
    <van-cell-group inset>
      <div class="price_title">
        <h3>
          <span class="icon">￥</span><span class="price">{{ Totol }}</span>
        </h3>
      </div>
      <van-divider
        dashed
        :style="{ color: '#1989fa', borderColor: '#1989fa', padding: '0 16px' }"
        >支付选择</van-divider
      >
      <van-cell
        title="建设银行储蓄卡(7288)"
        icon="https://storage.360buyimg.com/payment-assets/sdk/bank/CCB.png"
        is-link
        @click="changmeg((radio = '1'), '建设银行储蓄卡')"
      >
        <!-- 使用 title 插槽来自定义标题 -->
        <template #right-icon>
          <van-radio-group v-model="radio">
            <van-radio checked-color="#ee0a24" name="1"></van-radio>
          </van-radio-group>
        </template>
      </van-cell>
      <van-cell
        title="邮政银行借记卡(7288)"
        icon="https://storage.360buyimg.com/payment-assets/sdk/bank/POST.png"
        is-link
        @click="changmeg((radio = '2'), '邮政银行储蓄卡')"
      >
        <!-- 使用 title 插槽来自定义标题 -->
        <template #right-icon>
          <van-radio-group v-model="radio">
            <van-radio checked-color="#ee0a24" name="2"></van-radio>
          </van-radio-group>
        </template>
      </van-cell>
      <van-cell
        title="中国银行借记卡(7288)"
        icon="https://storage.360buyimg.com/payment-assets/sdk/bank/BOC.png"
        is-link
        @click="changmeg((radio = '3'), '中国银行储蓄卡')"
      >
        <!-- 使用 title 插槽来自定义标题 -->
        <template #right-icon>
          <van-radio-group v-model="radio">
            <van-radio checked-color="#ee0a24" name="3"></van-radio>
          </van-radio-group>
        </template>
      </van-cell>
      <van-cell
        title="白条(可用¥3000.00)"
        icon="	https://storage.360buyimg.com/payment-assets/sdk/icon/BAITIAO_2.0.png"
        is-link
        @click="changmeg((radio = '4'), '白条')"
      >
        <!-- 使用 title 插槽来自定义标题 -->
        <template #right-icon>
          <van-radio-group v-model="radio">
            <van-radio checked-color="#ee0a24" name="4"></van-radio>
          </van-radio-group>
        </template>
      </van-cell>
    </van-cell-group>

    <van-cell-group class="bottom_btn">
      <van-cell
        style="line-height: 14px"
        title="微信支付"
        icon="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/weixin.png"
        is-link
        label="仅安装微信6.0.2 及以上版本客户端使用"
        @click="changmeg((radio = '5'), '微信')"
      >
        <!-- 使用 title 插槽来自定义标题 -->
        <template #right-icon>
          <van-radio-group v-model="radio">
            <van-radio checked-color="#ee0a24" name="5"></van-radio>
          </van-radio-group>
        </template>
      </van-cell>
    </van-cell-group>
    <van-cell-group class="bottom_btn">
      <van-cell
        style="line-height: 14px"
        title="刷脸支付"
        icon="https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/Facepaymentidon.png"
        is-link
        label="请确认是否开通生物支付"
        @click="changmeg((radio = '6'), '刷脸支付')"
      >
        <!-- 使用 title 插槽来自定义标题 -->
        <template #right-icon>
          <van-radio-group v-model="radio">
            <van-radio checked-color="#ee0a24" name="6"></van-radio>
          </van-radio-group>
        </template>
      </van-cell>
    </van-cell-group>
    <div class="banxxx"></div>
    <div class="zhifu">
      <van-button
        style="width: 100%"
        @click="gotoPay"
        round
        color="linear-gradient(to right, #ff6034, #ee0a24)"
        >{{ meg }}支付￥{{ Totol }}</van-button
      >
    </div>
    <van-overlay :show="payshow" @click="payshow = false">
      <div class="wrapper" @click.stop>
        <div class="block">
          <div class="mask">
            <van-loading
              :vertical="true"
              style="left: 50%; top: 50%; transform: translate(-50%, -50%)"
              color="#ffffff"
              v-if="payload"
              >正在支付...</van-loading
            >
          </div>
          <video ref="video" width="100%" height="200" autoplay></video>
          <canvas ref="canvas" v-show="cas" width="500" height="480"></canvas>
        </div>
      </div>
    </van-overlay>
  </div>
</template>
<script>
import { mapState } from "vuex";
import { setItem, getItem, removeItem } from "../utils/storage";

export default {
  data() {
    return {
      radio: "5",
      meg: "微信",
      countDownTime: 160,
      times: 0,
      payshow: false,
      cas: false,
      facestatus: "",
      payload: false,
      faceValidation: {
        pid: 0,
        Image: "",
      },
    };
  },
  created() {},
  mounted() {
    this.socketApi.initWebSocket();
  },
  methods: {
    goBack() {
      this.$dialog
        .confirm({
          title: "确认要离开收银台?",
          message: "您的订单在0小时29分钟内未支付将被取消,请尽快完成支付。",
          theme: "round-button",
          confirmButtonText: "确认离开",
          cancelButtonText: "继续支付",
        })
        .then(() => {
          // let item = ;
          var arry2 = [];
          let a = this.ordernum;
          var date = new Date();

          var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
          var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
          var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

          var hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
          var minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
          var seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59)
          var currentFormatDate =
            year +
            "-" +
            month +
            "-" +
            day +
            " " +
            hours +
            ":" +
            minutes +
            ":" +
            seconds;
          this.CheckoutList.map((item, index) => {
            arry2.push(
              Object.assign({}, item, {
                OrderNum: a,
                addTime: currentFormatDate,
              })
            );
          });
          console.log(arry2);
          this.addReceivedpay(arry2);
          let endMsRes = new Date().getTime() + 1800000;
          //Setitem 为封装 localStoryge 方法
          setItem("myEndTime", JSON.stringify(endMsRes));
          this.$router.push("/Cat");
        })
        .catch(() => {
          // on cancel
        });
    },
    async addReceivedpay(item) {
      const { data: res } = await this.$http.post("addreceived", item);

      if (res.status == 200) {
        this.$store.commit("setCheckoutList", null);
      }
    },
    changmeg(val, msg) {
      this.meg = msg;
    },
    gotoPay() {
      this.$toast.loading({
        forbidClick: true,
        message: "加载中...",
        loadingType: "spinner",
      });
      setTimeout(() => {
        this.$toast.clear();
        if (this.meg === "刷脸支付") {
          this.getFacepaymentStatus();
        } else {
          this.$router.push({ name: "mjrpay", params: { msg: this.meg } });
        }
      }, 1500);
    },
    async getFacepaymentStatus() {
      const { data: res } = await this.$http.get("isFacePaymentOpen", {
        params: { id: this.$store.state.emailLogin[0].userID },
      });
      this.facestatus = res.isface.facestatus;
      if (res.isface.facestatus == "false") {
        this.$toast("您尚未开通刷脸支付！");
      } else {
        this.payload = true;
        this.payshow = true;
        this.callCamera();
        setTimeout(() => {
          this.photograph();
        }, 1500);
      }
    },
    callCamera() {
      // H5调用电脑摄像头API
      navigator.mediaDevices
        .getUserMedia({
          video: true,
        })
        .then((success) => {
          // 摄像头开启成功
          this.$refs["video"].srcObject = success;
          // 实时拍照效果
          this.$refs["video"].play();
        })
        .catch(() => {
          console.error("摄像头开启失败，请检查摄像头是否可用！");
        });
    },
    photograph() {
      let ctx = this.$refs["canvas"].getContext("2d");
      // 把当前视频帧内容渲染到canvas上
      ctx.drawImage(this.$refs["video"], 0, 0, 640, 480);
      // 转base64格式、图片格式转换、图片质量压缩
      let imgBase64 = this.$refs["canvas"].toDataURL("image/jpeg", 0.7); // 由字节转换为KB 判断大小
      // console.log(imgBase64);
      this.faceValidation.Image = imgBase64;
      this.faceValidation.pid =
        this.$store.state.emailLogin[0].userID.toString();
      this.FaceVerification();
    },
    async FaceVerification() {
      const { data: res } = await this.$http.post(
        "FaceVerification",
        this.faceValidation
      );
      console.log(res);
      if (res.data.IsMatch == true) {
        this.QueryBalance();
        console.log("人脸验证通过！");
      }
      if (res.data.code == "InvalidParameterValue.NoFaceInPhoto") {
        this.$toast("人脸不符！");
      }
    },
    base64ImgtoFile(dataurl, filename = "file") {
      let arr = dataurl.split(",");
      let mime = arr[0].match(/:(.*?);/)[1];
      let suffix = mime.split("/")[1];
      let bstr = atob(arr[1]);
      let n = bstr.length;
      let u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      return new File([u8arr], `${filename}.${suffix}`, {
        type: mime,
      });
    },
    closeCamera() {
      if (!this.$refs["video"].srcObject) return;
      let stream = this.$refs["video"].srcObject;
      let tracks = stream.getTracks();
      tracks.forEach((track) => {
        track.stop();
      });
      this.$refs["video"].srcObject = null;
    },
    async addReceived() {
      var arry2 = [];

      var date = new Date();

      var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

      var hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59)
      var currentFormatDate =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      try {
        this.CheckoutList.map((item, index) => {
          arry2.push(
            Object.assign({}, item, {
              userID: this.emailLogin[0].userID,
              OrderNum: this.getProjectNum + Math.floor(Math.random() * 10000),
              newTime: currentFormatDate,
              orderState: "待发货",
              addressID: this.$store.state.SelectAddress.id,
            })
          );
        });
      } catch (error) {}

      const { data: res } = await this.$http.post("addAllOrder", arry2);

      //    console.log(res);
    },
    async addallorder() {
      var arry2 = [];

      var date = new Date();

      var year = date.getFullYear(); //年 ,从 Date 对象以四位数字返回年份
      var month = date.getMonth() + 1; //月 ,从 Date 对象返回月份 (0 ~ 11) ,date.getMonth()比实际月份少 1 个月
      var day = date.getDate(); //日 ,从 Date 对象返回一个月中的某一天 (1 ~ 31)

      var hours = date.getHours(); //小时 ,返回 Date 对象的小时 (0 ~ 23)
      var minutes = date.getMinutes(); //分钟 ,返回 Date 对象的分钟 (0 ~ 59)
      var seconds = date.getSeconds(); //秒 ,返回 Date 对象的秒数 (0 ~ 59)
      var currentFormatDate =
        year +
        "-" +
        month +
        "-" +
        day +
        " " +
        hours +
        ":" +
        minutes +
        ":" +
        seconds;
      console.log(this.$store.state.SelectAddress.id);
      this.recList.map((item, index) => {
        arry2.push(
          Object.assign({}, item, {
            newTime: currentFormatDate,
            orderState: "待发货",
            addressID: this.$store.state.SelectAddress.id,
          })
        );
      });

      const { data: res } = await this.$http.post("addAllOrder", arry2);
      console.log(res);
    },
    async removeOrder() {
      const { data: res } = await this.$http.get("deleOrder", {
        params: { num: this.OrderNum },
      });
      if (res.status == 200) {
        window.localStorage.removeItem("time");
        window.localStorage.removeItem("OrderNum");
        window.localStorage.removeItem("myEndTime");
      }
    },
    //增加消费支出
    async addConsumptionInfo() {
      let data = {
        conType: "购物-消费",
        time: new Date(),
        Expenditure: this.Totol,
        Benefit: 0,
        typeIcon:
          "https://sss-1306551685.cos.ap-guangzhou.myqcloud.com/MobileShop/zhichu_gw.png",
        userID: this.emailLogin[0].userID,
      };
      const { data: res } = await this.$http.post("addConsumptionInfo", data);
      console.log(res);
    },
    //扣除相应金额
    async DeductionAmount() {
      const { data: res } = await this.$http.post("ExcludingAmount", {
        price: this.Totol,
        uid: this.emailLogin[0].userID,
      });
      console.log(res);
    },
    //查询余额
    async QueryBalance() {
      const { data: res } = await this.$http.get("QueryAmount", {
        params: { uid: this.emailLogin[0].userID },
      });
      console.log(res);
      console.log(this.emailLogin[0].userID);
      this.closeCamera();

      this.$toast.success("支付成功");
      setTimeout(() => {
        if (res.Amount.Account_balance > this.Totol) {
          this.payshow = false;
          this.payload = false;
          this.radio = "5";
          this.addReceived();
          this.removeOrder();
          this.sendOrderMsg();
          this.addConsumptionInfo();
          this.$toast.clear();
          this.value = "";
          window.localStorage.removeItem("Totol");
          window.localStorage.removeItem("checkoutList");
          window.localStorage.removeItem("recList");
          this.DeductionAmount();
          this.$router.push("/Cat");
        } else {
          this.$toast("余额不足！");
        }
      }, 1200);
    },
    //发送消息
    async sendOrderMsg() {
      console.log("发送了");
      let data = {
        userID: this.emailLogin[0].userID,
        receive_id: 1,
        Nickname: this.emailLogin[0].Nickname,
        Time: new Date(),
        title: "来自" + this.emailLogin[0].Nickname + "的订单！",
        msgType: 12, //代表订单消息
        textType: "订单",
      };
      this.socketApi.handleSendMsg(data);
    },
  },
  computed: {
    ...mapState(["Totol", "emailLogin", "CheckoutList", "recList", "OrderNum"]),
    ordernum() {
      var orderCode = 0;
      for (
        var i = 0;
        i < 6;
        i++ //6位随机数，用以加在时间戳后面。
      ) {
        orderCode += Math.floor(Math.random() * 10);
      }
      orderCode = new Date().getTime() + orderCode; //时间戳，用来生成订单号。

      return orderCode;
    },
    getProjectNum() {
      const projectTime = new Date(); // 当前中国标准时间
      const Year = projectTime.getFullYear(); // 获取当前年份 支持IE和火狐浏览器.
      const Month = projectTime.getMonth() + 1; // 获取中国区月份
      const Day = projectTime.getDate(); // 获取几号
      var CurrentDate = Year;
      if (Month >= 10) {
        // 判断月份和几号是否大于10或者小于10
        CurrentDate += Month;
      } else {
        CurrentDate += "0" + Month;
      }
      if (Day >= 10) {
        CurrentDate += Day;
      } else {
        CurrentDate += "0" + Day;
      }
      return CurrentDate;
    },
  },
};
</script>
<style lang="less" scoped>
.price_title {
  width: 100%;
  h3 {
    text-align: center;
    padding: 10px;
    line-height: 40px;
    color: #fa200c;
    position: relative;
    top: 10px;
    .icon {
    }
    .price {
      font-size: 1.6rem;
    }
  }
}
.van-cell {
  height: 60px;
  padding-top: 20px;
}
.van-icon__image {
  width: 2em;
  height: 2em;
  object-fit: contain;
}
.bottom_btn {
  margin-top: 15px;
}
.zhifu {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  height: 50px;
  background: #fff;
  padding: 1rem;
}
.banxxx {
  height: 11.25rem;
  background: #fff;
}
.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.block {
  width: 200px;
  height: 200px;
  // background-color: #fff;
}
.mask {
  width: 201px;
  height: 151px;
  /* background: red; */
  /* top: 10px; */
  margin-top: 24px;
  position: absolute;
  /* background: rgb(255 255 255 / 64%); */
  background: rgba(253, 253, 253, 0.6);
}
</style>